<template>
  <div
    :style="{ backgroundColor: lessonDetail.info[0].video && 'black' }"
    class="course-learn"
  >
    <loading-page
      background-color="https://fangti-mcdn.oss-cn-beijing.aliyuncs.com/appstatic/background/bg_learn.png"
      img="pic_read@2x.png"
    >
      <div class="course-learn-detail">
        <nav-bar
          v-if="!lessonDetail.info[0].video"
          :background="
            !lessonDetail.info[0].video ? '' : plant === 'wx' ? 'none' : 'black'
          "
          :color="!lessonDetail.info[0].video ? '' : ''"
          class="nav-bar-position"
        >
          {{ lessonDetail.info[0].video ? "" : "学一学" }}
        </nav-bar>
        <white-space/>

        <section class="course-title" v-if="isReadingTitle">
          <my-img :src="lessonList.picture" class-name="title-img"/>
        </section>

        <section class="course-content" v-else>
          <template v-if="!lessonDetail.info[0].video">
            <swiper
              :current="current"
              :touchable="false"
              @change="change"
              class="swiper"
            >
              <swiper-item
                :key="index"
                class="swiper-item"
                v-for="(v, index) in lessonDetail.info"
              >
                <my-img :src="v.picture" class-name="swiper-img"/>

                <p class="p">
                  <!--                  <rich-text :nodes="content"></rich-text>-->
                  <!--                  <view v-if="">-->
                  <!--                    {{  }}-->
                  <!--                  </view>-->
                  <!--                  <parser :html="!isPlaying ? v.content : content" v-if="plant==='app'"/>-->
                  <rich-text :nodes="content ? content : v.content"/>
                </p>
              </swiper-item>
              <swiper-item/>
            </swiper>

            <div class="wrap" v-if="currentRecordIsFinish && !isPlaying">
              <my-img class-name="hand" src="handler.gif" @touchend="playNext"/>
            </div>
          </template>

          <template v-else>
            <video
              :direction="direction"
              :src="lessonDetail.info[0].video"
              :style="{ height: plant === 'wx' ? '100vh' : '100vh' }"
              @ended="playNext"
              :controls="plant !== 'wx'"
              :show-fullscreen-btn="false"
              :show-play-btn="false"
              :enable-progress-gesture="true"
              :title="false"
              :vslide-gesture-in-fullscreen="false"

              @fullscreenchange="onFullScreenChange"
              class="video"
              id="myVideo"
            >
              <img
                class="img"
                @tap="NavigateBack"
                alt=""
                src=""
              />
              <cover-image
                class="img"
                @tap="NavigateBack"
                alt=""
                src="https://fangti-mcdn.oss-cn-beijing.aliyuncs.com/appstatic/img/ft2/nav_ico_bach_h@2x.png"
              ></cover-image>
            </video>
          </template>
        </section>
      </div>
    </loading-page>
  </div>
</template>

<script>
  import { mapActions, mapState } from "vuex";
  import { NavigateBack, RedirectTo } from "../../utils/router";
  import LoadingPage from "../../component/loading-page/loading-page";
  import Parser from "../../component/parser/index";

  export default {
    name: "course-learn",
    components: { LoadingPage, Parser },
    data() {
      return {
        isReadingTitle: true,
        current: 0,
        id: 0,
        type_id: 0,

        innerAudioContext: "",
        content: "",
        currentRecordIsFinish: false,

        direction: 0,
        isPlaying: false,

        time: [],

        plant: "wx"
      };
    },
    computed: {
      ...mapState("Course", ["lessonDetail", "lessonList"])
    },
    methods: {
      ...mapActions("Course", ["reqLessonDetail", "reqCompleteTask"]),
      ...mapActions("Tools", ["stopPlay", "playContentPageVoice", "hideLoading"]),
      RedirectTo,
      NavigateBack,

      onFullScreenChange(e) {
        let { direction, fullScreen } = e.detail;

        console.log(e);
        if (!fullScreen) {
          // #ifdef  MP-WEIXIN
          this.direction = 90;
          //#endif

          // #ifdef  APP-PLUS
          this.direction = -90;
          // #endif
        } else {
          this.direction = 0;
        }
        console.log(this.direction);
      },

      async hideLoadingPage() {
        let time = setTimeout(async () => {
          this.hideLoading();
          if (this.lessonDetail.info[0].video) {
            this.videoContext = uni.createVideoContext("myVideo");


            // #ifdef  MP-WEIXIN
            this.videoContext.hideStatusBar();

            this.videoContext.requestFullScreen({ direction: 90 });
            this.direction = 90;
            //#endif

            // #ifdef  APP-PLUS
            this.videoContext.requestFullScreen();
            this.direction = -90;
            //#endif
            this.videoContext.play();
          } else {
            this.play();
          }
          // #ifdef  MP-WEIXIN

          this.videoContext.hideStatusBar();
          //#endif

          // 加载 数据
        }, 3000);
        this.time.push(time);
      },

      /**
       * @description 标题读取完毕后调用
       * @returns {Promise<void>}
       */
      async readTitleFinishAndHideTitlePage() {
        setTimeout(async () => {
          this.isReadingTitle = false;
        }, 2000);
      },

      /**
       * @description 播放
       */

      play() {
        this.playLearnVoice();
      },

      playLyrics({ currentCharacter }) {
        const { current, lessonDetail } = this;
        const { content } = lessonDetail.info[current];
        const punctuation = [
          `，`,
          `。`,
          `》`,
          "、",
          `《`,
          `-`,
          `！`,
          `？`,
          `：`,
          `“`,
          `”`,
          "‘",
          "’"
        ];
        const arr = [...content];
        const character = arr.splice(currentCharacter, 1);
        character[0] &&
        arr.splice(
          currentCharacter,
          0,
          punctuation.includes(character[0])
            ? `<span>${ character[0] || "" }</span>`
            : `<span style="color:#00BD81;display: inline">${ character[0] ||
            "" }</span>`
        );
        this.content = `<span>${ arr.join("") }</span>`;
      },

      playLearnVoice: function () {
        const { current, lessonDetail } = this;
        const { audio, content } = lessonDetail.info[current];

        if (!this.innerAudioContext) {
          this.innerAudioContext = uni.createInnerAudioContext(); // 获取实例
        }
        const { innerAudioContext } = this;
        innerAudioContext.stop();

        if (!audio) {
          return;
        }

        innerAudioContext.src = audio;

        innerAudioContext.onCanplay(() => {
          // #ifdef  APP-PLUS

          setTimeout(() => {
            this.isPlaying = true;
          });
          //#endif

          this.currentRecordIsFinish = false;
          innerAudioContext.duration;
          const { duration } = innerAudioContext;
          console.log(duration);
          const time = content.length / duration; // 多少秒换一个字
          const _time = time < 150 ? 150 : time; // 减少页面刷新频率
          // #ifdef  APP-PLUS
          clearInterval(innerAudioContext._playerTime);
          let playerTime = () => {
            const { currentTime } = innerAudioContext;
            const currentCharacter = Math.ceil(
              time * (currentTime === 0 ? 9999999999 : currentTime)
            );
            this.playLyrics({ currentCharacter });
          };
          // setTimeout(() => {
          innerAudioContext._playerTime = setInterval(() => {
            playerTime();
          }, _time);
          // }, 500)
          //#endif
        });

        innerAudioContext.onPlay(() => {
          const { duration } = innerAudioContext;
          console.log(duration, innerAudioContext.duration);
        });

        innerAudioContext.onTimeUpdate(() => {
          this.isPlaying = true;
          const { duration } = innerAudioContext;
          const time = content.length / duration; // 多少秒换一个字
          const { currentTime } = innerAudioContext;
          const currentCharacter = Math.ceil(time * currentTime);
          // #ifdef  MP-WEIXIN
          this.playLyrics({ currentCharacter });
          // #endif
        });

        innerAudioContext.onEnded(() => {
          this.isPlaying = false;
          setTimeout(() => {
            this.currentRecordIsFinish = true;
          }, 2000);
        });
        innerAudioContext.play();
      },

      async playNext() {
        const { id, type_id, lessonDetail, current } = this;
        const isVideo = lessonDetail.info[0].video || "";
        await this.reqCompleteTask({
          id: lessonDetail.info[current].id,
          type_id
        });
        if (this.lessonDetail.info.length === this.current + 1 || isVideo) {
          this.videoContext && this.videoContext.exitFullScreen();
          setTimeout(() => {
            return this.RedirectTo({
              url: "/pages_course/course_finish/course_finish",
              query: { id, type_id, count: 5 }
            });
          }, 1000);
        }
        this.current = this.current + 1;

        // 如果不是视频 则可以播放下一个，否则 不可以
        if (!isVideo) {
          const voicePath = lessonDetail.info[current].audio;
          this.playLearnVoice({ voicePath });
        }
      },

      async change(e) {
        this.isPlaying = false;

        // #ifdef  APP-PLUS
        clearInterval(this.innerAudioContext._playerTime);
        // #endif

        const { current } = e.detail;
        const { id, type_id, lessonDetail, innerAudioContext } = this;

        innerAudioContext.stop();

        if (this.current < current) {
          await this.reqCompleteTask({
            id: lessonDetail.info[current - 1].id,
            type_id
          });
        }
        this.current = current;
        const { content } = lessonDetail.info[current] || { content: "" };
        this.content = content;
        if (this.lessonDetail.info.length === this.current) {
          return this.RedirectTo({
            url: "/pages_course/course_finish/course_finish",
            query: { id, type_id, count: 5 }
          });
        }
        this.playLearnVoice();
      }
    },
    async onLoad(query) {
      const { id, type_id } = query;
      this.id = id;
      this.type_id = type_id;
      await this.reqLessonDetail({ id, type_id });
      await this.hideLoadingPage();
      await this.readTitleFinishAndHideTitlePage();

      // #ifdef  MP-WEIXIN
      this.plant = "wx";
      //#endif

      // #ifdef  APP-PLUS
      this.plant = "app";
      //#endif
    },

    // 卸载页面时
    onUnload() {
      const { time, videoContext, innerAudioContext } = this;
      time.forEach(item => clearTimeout(item));
      // #ifdef  APP-PLUS
      clearInterval(this.innerAudioContext._playerTime);
      // #endif
      // 停止播放视频时
      if (videoContext) {
        // 旋转视频
        this.videoContext && this.videoContext.exitFullScreen();
        this.stopPlay();
      } else {
        setTimeout(() => {
          innerAudioContext && innerAudioContext.stop();
          innerAudioContext.destroy();
        });
      }
    },
    onShow() {
      const { videoContext, innerAudioContext, currentRecordIsFinish } = this;

      if (videoContext) {
      } else {
        !currentRecordIsFinish && innerAudioContext && innerAudioContext.play();
      }
    },
    onHide() {
      const {
        time,
        videoContext,
        innerAudioContext,
        currentRecordIsFinish
      } = this;

      if (videoContext) {
      } else {
        !currentRecordIsFinish && innerAudioContext && innerAudioContext.pause();
      }
    }
  };
</script>

<style lang="scss">
  @import "../../uni";

  .course {
    &-learn {
      &-detail {
        background: #fff;
      }
    }

    &-title {
      .title-img {
        width: 100vw;
        height: upx(1100);
      }
    }

    &-content {
      .swiper {
        min-height: 100vh;

        &-item {
          width: upx(750);
          min-height: 100vh;
        }

        &-img {
          width: upx(750);
          height: upx(750);
        }
      }

      p {
        padding: upx(30) upx(24);
        @include ft(42, #273c3d, 400);
        font-family: KaiTi, SimSun, FangSong, serif !important;
        line-height: 1.5em;
        text-indent: 2em;
        text-align: justify;
        letter-spacing: 0.15em;
        /*transition: color .3s ease-in-out;*/
      }

      .wrap {
        z-index: 9999;
        position: fixed;
        bottom: 0;
        right: 0;
        width: 20vw;
        height: 20vh;
      }

      .hand {
        position: fixed;
        right: upx(64);
        bottom: upx(64);
        width: upx(300);
        height: upx(100);
      }

      .video {
        position: absolute;
        bottom: 0;
        width: 100vw;

        .img {
          z-index: 999999;
          position: absolute;
          top: upx(20);
          left: upx(20);
          width: upx(50);
          height: upx(50);
        }
      }
    }

    .controls-title {
    }

    .controls-play {
      left: upx(50);
    }

    .img {
      z-index: 999999;
      position: absolute;
      width: upx(50);
      height: upx(50);
      top: 50%;
      margin-top: -50rpx;
    }
  }
</style>
